/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package postmaster;

import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author maniksin
 */
public class peer_timer extends TimerTask {
    
    public static final int HELLO_TIMER = 0;
    public static final int NEIGHBOR_DEAD = 1;
    
    public static final long NEIGHBOR_DEAD_TIMER = 15 * 1000;  //15seconds
    public static final long HELLO_INTERVAL = 5 * 1000; // 5 seconds
    
    private peer p;
    private int timer_type;
    private postmaster pm;
    
    public peer_timer (peer p, postmaster pm, int type) {
     this.p = p;
     this.timer_type = type;
     this.pm = pm;
    }

    @Override
    public void run() {
        
        switch(timer_type) {
            case HELLO_TIMER:
                pm.sayHello(p);
                pm.start_monitoring(p);
                break;
            case NEIGHBOR_DEAD:
                if (p.state == peer_state.PEER_RESPONDING) {
                    p.state = peer_state.PEER_RESPONSE_AWAITED;
                    long delay = peer_timer.NEIGHBOR_DEAD_TIMER;
                    p.neighbor_timer.schedule(
                            new peer_timer(p, pm, peer_timer.NEIGHBOR_DEAD), delay);
                } else {
                    Logger.global.log(Level.WARNING, "Lost connection to peer {0}", p.get_name());
                    p.state = peer_state.PEER_DEAD;                    
                    p.remove(pm);
                }
                break;
            default:
                Logger.global.log(Level.WARNING, "Unknown timer event {0} received. Not handled", timer_type);
                break;
        }
    }
}
